package com.example.coapdemo.web;

import cn.hutool.json.JSONObject;
import org.eclipse.californium.core.CoapResource;
import org.eclipse.californium.core.coap.CoAP;
import org.eclipse.californium.core.server.resources.CoapExchange;
import org.springframework.util.CollectionUtils;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

import static com.example.coapdemo.utils.CborUtil.convertObjFromBytes;

public class CborController extends CoapResource {
    public CborController(String name) {
        super(name);
    }


    @Override
    public void handlePOST(CoapExchange exchange) {
        // 重写处理POST请求的方法
        List<String> uriQuery = exchange.getRequestOptions().getUriQuery();
        System.out.println("Post cbor parameters: " + uriQuery);
        if (!CollectionUtils.isEmpty(uriQuery)) {
            for (String s : uriQuery) {
                String[] split = s.split("=");
                System.out.println(String.format("k= %s,v=%s", split[0], split[1]));
            }
        }
        byte[] requestPayload = exchange.getRequestPayload();
        JSONObject realBody = convertObjFromBytes(requestPayload, JSONObject.class);
        System.out.println(String.format("Post cbor request <<<  %s,%s ,cbor Arr=%s",
                realBody,
                new Date(),
                Arrays.toString(requestPayload)
        ));
        exchange.respond(CoAP.ResponseCode.CONTENT, String.format("Post cbor !, <<< %s >>> ", realBody));

    }
}
